﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DotNetOpenAuth.OpenId;
using DotNetOpenAuth.OpenId.RelyingParty;
using DotNetOpenAuth.OpenId.Extensions.SimpleRegistration;
using DotNetOpenAuth.OpenId.Extensions.AttributeExchange;

namespace PUCIT.eFCS
{
    public partial class Login : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
          // LogIn("efcssac@gmail.com", "Mehwish Khursheed");
         //LogIn("bsef09m014@pucit.edu.pk", "Maryam Wajid");
           // LogIn("bsef09m022@pucit.edu.pk", "Naila akbar");

            OpenIdRelyingParty rp = new OpenIdRelyingParty();
            var response = rp.GetResponse();
            if (response != null)
            {
                switch (response.Status)
                {
                    case AuthenticationStatus.Authenticated:

                        ClaimsResponse sregResponse = response.GetExtension<ClaimsResponse>();
                        FetchResponse axResponse = response.GetExtension<FetchResponse>();
                        string nick = response.FriendlyIdentifierForDisplay;

                        string homepage = response.ClaimedIdentifier;
                        string email = "none@none.com";

                        if (sregResponse != null)
                        {
                            nick = string.IsNullOrEmpty(sregResponse.Nickname) ? sregResponse.FullName : sregResponse.Nickname;
                            email = sregResponse.Email;
                        }

                        if (String.IsNullOrEmpty(nick) && axResponse != null && axResponse.Attributes.Contains(WellKnownAttributes.Name.First) && axResponse.Attributes.Contains(WellKnownAttributes.Name.Last))
                        {
                            nick = axResponse.GetAttributeValue(WellKnownAttributes.Name.First) + " " + axResponse.GetAttributeValue(WellKnownAttributes.Name.Last);
                        }


                        Session["GoogleIdentifier"] = response.ClaimedIdentifier.ToString();
                        LogIn(email, nick);
                        break;
                    case AuthenticationStatus.Canceled:
                        Session["GoogleIdentifier"] = "Cancelled.";
                        break;
                    case AuthenticationStatus.Failed:
                        Session["GoogleIdentifier"] = "Login Failed.";
                        break;
                }
            }
            else
            {
                if (!Page.IsPostBack)
                {
                    string discoveryUri = "https://www.google.com/accounts/o8/id";
                    OpenIdRelyingParty openid = new OpenIdRelyingParty();
                    var URIbuilder = new UriBuilder(Request.Url) { Query = "" };
                    IAuthenticationRequest req = openid.CreateRequest(discoveryUri, URIbuilder.Uri, URIbuilder.Uri);
                    IAuthenticationRequest t = openid.CreateRequest(discoveryUri, URIbuilder.Uri, URIbuilder.Uri);

                    ClaimsRequest sregRequest = new ClaimsRequest();
                    sregRequest.Email = DemandLevel.Require;
                    sregRequest.Nickname = DemandLevel.Request;
                    sregRequest.FullName = DemandLevel.Request;
                    sregRequest.Country = DemandLevel.Request;
                    sregRequest.Gender = DemandLevel.Request;
                    sregRequest.BirthDate = DemandLevel.Request;
                    req.AddExtension(sregRequest);

                    FetchRequest axRequest = new FetchRequest();
                    axRequest.Attributes.AddRequired(WellKnownAttributes.Name.First);
                    axRequest.Attributes.AddRequired(WellKnownAttributes.Name.Last);
                    axRequest.Attributes.AddRequired(WellKnownAttributes.BirthDate.WholeBirthDate);
                    axRequest.Attributes.AddRequired(WellKnownAttributes.Person.Gender);
                    axRequest.Attributes.AddRequired(WellKnownAttributes.Preferences.Language);
                    axRequest.Attributes.AddRequired(WellKnownAttributes.Company.CompanyName);
                    axRequest.Attributes.AddRequired(WellKnownAttributes.Company.JobTitle);
                    axRequest.Attributes.AddRequired(WellKnownAttributes.Contact.Phone.Mobile);
                    req.AddExtension(axRequest);



                    req.RedirectToProvider();
                }
            }
        }
        protected void btnGoogleLogin_Click(object sender, CommandEventArgs e)
        {
            //string discoveryUri = e.CommandArgument.ToString();
            //OpenIdRelyingParty openid = new OpenIdRelyingParty();
            //var URIbuilder = new UriBuilder(Request.Url) { Query = "" };
            //var req = openid.CreateRequest(discoveryUri, URIbuilder.Uri, URIbuilder.Uri);
            //req.RedirectToProvider();
        }

        protected void LogIn(string gmail, string nick)
        {
            Session["valid"] = "";
            Session["email"] = gmail;
            Session["name"] = nick;

            Business.BusinessClass bc = new Business.BusinessClass();


            //getting userid from email
            int uId = bc.GetUserIdByEmail(gmail);
            //getting category id from userId
            int cId = 2;
            if (uId > 0)
            {
                cId = bc.GetCatIdbyUserId(uId);
            }

            Session["userId"] = uId;
            Session["categoryId"] = cId;
            Session["username"] = nick;
            Session["attachments"] = new List<Business.Attachments>();

            string role = parseEmail(gmail);

            if (role.Equals("student"))
            {
                Session["role"] = "student";
                if (uId > 0)
                {
                    Response.Redirect("~/Default.aspx");
                }
                else
                {
                    Session["role"] = "NewStudent";
                    Response.Redirect("~/Default.aspx");
                }
            }
            else if (role.Equals("stationUser"))
            {
                Session["role"] = "stationUser";
                if (uId > 0)
                {
                    Response.Redirect("~/Default.aspx");
                }
                else
                {                   
                    Response.Redirect("~/Validation.aspx");
                }
            }     
 
            else if (role.Equals("administration"))
            {
                Session["role"] = "admin";
                Session["valid"] = "Admin";
                Response.Redirect("~/Validation.aspx");
            }
                // for sac for now
            else if (role.Equals("other") && uId > 0)
            {
                //for sac , ds , principal
                Session["role"] = "Other";
                Response.Redirect("~/Default.aspx");
            }
            /*

            String email = gmail;// admin account
            

            String userName = "";
            int userId = -1;
            Boolean verificationFlag = true;

            userName = email.Substring(0, email.IndexOf('@'));
            Business.BusinessClass businessObject = new Business.BusinessClass();
            

            int cId = businessObject.AddUser(userName, email);


            //userId   = businessObject.GetUserIdByUserName(email);
            userId = businessObject.GetUserIdByEmail(email);  // userenteries function = getuserid()
            //getByIdentity.
            userName = businessObject.GetCategoryName(cId);   //from USERs table
            //   verificationFlag=businessObject.isVerified(email);
            //naila
            userId = 8;
            cId = 1;

            //mam mehwish
            // userId = 4;
            // cId = 2; 
            if (userId != -1 && verificationFlag) // User Exists
            {
                Session["userId"] = userId;
                Session["categoryId"] = cId;
                Session["username"] = nick;
                Session["attachments"] = new List<Business.Attachments>();

                if (cId == 6) // Admin
                {
                    Response.Redirect("~/ViewTemplateList.aspx");
                }
                
                else if (cId == 1) // student
                {
                    Response.Redirect("~/ViewCirculationList.aspx");
                }
                else  //StationUser
                {
                    Response.Redirect("~/ViewToDoList.aspx");
                }
            }
            else
            {
                Response.Redirect("~/Login.aspx");
            }             


            */
        }

        protected string parseEmail(string email)
        {
            string str = email.Substring(0, email.IndexOf('@'));

            string prog = email.Substring(0, 3);
            string year = email.Substring(3, 3);
            string session = email.Substring(6, 1);
            string rollNo = email.Substring(7, 3);


            string role = null;

            if (email.EndsWith("pucit.edu.pk", StringComparison.OrdinalIgnoreCase))
            {
                if (prog == "bse" || prog == "bcs" || prog == "bit" || prog == "mit" || prog == "mcs" || prog == "gis")
                {
                    role = "student";

                    return role;

                    //string yt = year.Substring(1, 2);
                    //yt = "20" + yt;
                    //int y = Convert.ToInt32(yt);

                    //DateTime currentDate = System.DateTime.Today;
                    //int cy = currentDate.Year;
                    //cy = cy - y;
                    //int month = currentDate.Month;

                    //if (month >= 9 || month <= 2)
                    //{
                    //    smstr = cy * 2 - 1;
                    //}
                    //else if (month >= 3 || month <= 8)
                    //{
                    //    smstr = cy * 2;
                    //}
                }
                else
                {
                    role = "stationUser";
                    return role;
                }
            }
            else
            {
                role = "stationUser";
                //or else it is administration
                return role;
            }
        }
    }
}
